package tgc.edu.yzy.jdbc.score;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

import com.forte.qqrobot.beans.messages.result.GroupInfo;

import tgc.edu.yzy.CqrobotIndependentApplication;
import tgc.edu.yzy.controller.MyqqRobot;
import tgc.edu.yzy.custom.AjaxResult;
import tgc.edu.yzy.custom.CacheMap;
import tgc.edu.yzy.custom.RedisUtil;
import tgc.edu.yzy.custom.SpringContextUtil;
import tgc.edu.yzy.custom.TimeUtils;
import tgc.edu.yzy.custom.music.MusicFactory;
import tgc.edu.yzy.jdbc.XjMysqlJdbc;
import tgc.edu.yzy.jdbc.entity.ScoureUserForm;

public class ScooureController {
	private static CacheMap<String, String> scoureMap = new CacheMap<String, String>();
	/***
	 * 
	 * @param split
	 * @param qq
	 * @param group
	 * @return
	 */
	public AjaxResult get(String[] split, String qq, boolean group) {
		//建立临时 缓存，防止用户过分刷指令
		String string = scoureMap.get(qq);
		if(string!=null&&"1".equals(string)) {
			scoureMap.putPlusSeconds(qq, "2", 3);
			scoureMap.detect();
			return new AjaxResult(" 积分相关指令间隔3S哦，请您歇息一下。");
		}else if(string!=null&&"2".equals(string)){
			scoureMap.detect();
			return new AjaxResult(false, null);
		}
		scoureMap.putPlusSeconds(qq, "1", 3);
		
		if(split.length==2) {
			AjaxResult length2 = Length2(split[1],qq,group);
			if(length2.getSuccess())
				return length2;
		}
		//积分商城兑换系统
		AjaxResult scoureDuihuan = ScoureDuihuan(split,qq,group);
		
		return scoureDuihuan;
	}
	/***
	 * 积分兑换系统
	 * @param split
	 * @param qq
	 * @param group
	 * @return
	 */
	private AjaxResult ScoureDuihuan(String[] split, String qq, boolean group) {
		String msg = "";
		if(group) {
			msg+="[CQ:at,qq="+qq+"] ";
		}
		String IsNum = getNumber(split[1]);
		if(!StringUtils.isEmpty(IsNum)) {
			ScireStore scireStore = Score.getScireStore(IsNum);
			if(scireStore==null) {
				msg+="未查询到编号为："+IsNum+"的商品。";
				return new 	AjaxResult(msg);
			}else {
				Integer id = scireStore.getId();
				if(id==1) {
					//智能聊天服务
					Integer Tulin_Sum = 1;
					String czQQ = qq;
					if(split.length==3) {
						String Sum = getNumber(split[2]);
						Tulin_Sum = StringUtils.isEmpty(Sum)?1:Integer.parseInt(getNumber(Sum));
					}else if(split.length==4) {
						String Sum = getNumber(split[2]);
						Tulin_Sum = StringUtils.isEmpty(Sum)?1:Integer.parseInt(getNumber(Sum));
						String qQ = getNumber(split[3]);
						czQQ = StringUtils.isEmpty(qQ)?qq:qQ;
					}
					if(Tulin_Sum<0)Tulin_Sum = 1;
					return TuLin(qq, Tulin_Sum, scireStore.getNumber(), msg,czQQ);
				}else if(id == 2) {
					//购买增加好友位
					Integer Qu_Sum = 1;
					if(split.length==3) {
						String Sum = getNumber(split[2]);
						Qu_Sum = StringUtils.isEmpty(Sum)?1:Integer.parseInt(getNumber(Sum));
					}
					//
					if(Qu_Sum<0)Qu_Sum = 1;
					return QqUpdate(qq,Qu_Sum,"qq",scireStore.getNumber(),msg);
				}else if(id == 3) {
					//购买天使自动进群资格 一天
					if(split.length==3) {
						return updateGroup(qq,scireStore.getNumber(),msg,split[2],null);
					}else {
						return new AjaxResult("指令输入错误，请输入“积分#"+id+"#QQ群”！");
					}
				}else if(id == 4) {
					//购买天使自动进群永久资格
					if(split.length==3) {
						return updateGroup(qq,scireStore.getNumber(),msg,split[2],"永久授权");
					}else {
						return new AjaxResult("指令输入错误，请输入“积分#"+id+"#QQ群”！");
					}
				}else if(id == 5) {
					//QQ点歌
					if(split.length>=3) {
						return QqMusic(qq,split,scireStore.getNumber());
					}else {
						return new AjaxResult("指令输入错误，请输入“积分#"+id+"#歌名”！");
					}
				}else if(id == 6) {
					//QQ点歌
					if(split.length>=3) {
						return WyMusic(qq,split,scireStore.getNumber());
					}else {
						return new AjaxResult("指令输入错误，请输入“积分#"+id+"#歌名”！");
					}
				}else if(id == 7) {
					//给人点赞
					if(split.length==3) {
						qq = split[2];
					}
					return QQDianZan(qq,scireStore.getNumber(),msg);
				}
			}
		}
		return new AjaxResult(false, msg);
	}
	/***
	 * 给好友点赞
	 * @param qq
	 * @param number
	 * @param msg 
	 * @return
	 */
	private AjaxResult QQDianZan(String qq, Integer number, String msg) {
		Integer integer = MyqqRobot.groupPl.get("Dz"+qq);
		if(integer ==null) {
			Integer update = Score.update(qq, number, false,"点赞");
			if(update==2) {//扣除成功
				CqrobotIndependentApplication.msgSender.SENDER.sendLike(qq, 10);
				MyqqRobot.groupPl.putPlusSeconds("Dz"+qq,2,  TimeUtils.getRemainSecondsOneDay());
				msg += "兑换成功，已为你点赞，此服务一天只能兑换一次哦。";
			}else if(update==1){
				msg += "你积分不足"+number+",无法兑换此服务。";
			}else {
				msg += "系统繁忙,兑换失败。";
			}
			return new AjaxResult(msg);
		}else if(integer == 2){
			MyqqRobot.groupPl.putPlusSeconds("Dz"+qq, 5,  TimeUtils.getRemainSecondsOneDay());
			MyqqRobot.groupPl.detect();
			return new AjaxResult("点赞一天只能兑换一次哦。");
		}else {
			MyqqRobot.groupPl.detect();
			return new AjaxResult(false, null);
		}
		
	}
	/***
	 * 网易点歌
	 * @param qq
	 * @param split
	 * @param number5
	 * @return
	 */
	private AjaxResult WyMusic(String qq, String[] split, Integer number) {
		String msg = "";
		Integer update = Score.update(qq, number, false,"QQ点歌");
		if(update==2) {//扣除成功
			AjaxResult re = null;
			if(split.length==4) {
				re = MusicFactory.WyMusic(split[2], split[3]);
			}else{
				re = MusicFactory.WyMusic(split[2], null);
			}
			if(re.getSuccess()) {
				return re;
			}else {
				re.setSuccess(true);
				Score.update(qq, number, true,"QQ点歌失败");
				return re;
			}
		}else if(update==1){
			msg += "你积分不足"+number+",无法点歌。";
		}else {
			msg += "系统繁忙,兑换失败。";
		}
		return new AjaxResult(msg);
	}
	/***
	 * QQ点歌
	 * @param qq
	 * @param split
	 * @param number
	 * @return
	 */
	private AjaxResult QqMusic(String qq, String[] split, Integer number) {
		String msg = "";
		Integer update = Score.update(qq, number, false,"QQ点歌");
		if(update==2) {//扣除成功
			AjaxResult re = null;
			if(split.length==4) {
				re = MusicFactory.QQmusic(split[2], split[3]);
			}else{
				re = MusicFactory.QQmusic(split[2], null);
			}
			if(re.getSuccess()) {
				return re;
			}else {
				re.setSuccess(true);
				Score.update(qq, number, true,"QQ点歌失败");
				return re;
			}
		}else if(update==1){
			msg += "你积分不足"+number+",无法点歌。";
		}else {
			msg += "系统繁忙,兑换失败。";
		}
		return new AjaxResult(msg);
	}
	/***
	 *  添置自动同意进群的功能
	 * @param msg 
	 * @param number 
	 * @param qq 
	 * @param split 
	 * @return 
	 */
	private AjaxResult updateGroup(String qq, Integer number, String msg, String split,String creName) {
		ScoureUserForm updateGroupIsNull = Score.updateGroupIsNull(split);
		if(updateGroupIsNull!=null&&"永久授权".equals(updateGroupIsNull.getCreateName())) {
			return new AjaxResult("兑换失败,“"+split+"”此群已是永久授权自动同意的群。");
		}else if(updateGroupIsNull!=null&&StringUtils.isEmpty(creName)) {
			return new AjaxResult("兑换失败,此群已是可以自动同意进群的群聊。");
		}
		String cre_Name = creName==null?"+1":creName;
		Integer update = Score.update(qq, number, false,"购买加群资格"+cre_Name);
		if(update==2) {//扣除成功
			String Group_Name = "";
			String Group_Intro = "";
			try {
				GroupInfo groupInfo =CqrobotIndependentApplication.msgSender.GETTER.getGroupInfo(split);
				Group_Intro = StringUtils.isEmpty(groupInfo.getCompleteIntro())?"-":groupInfo.getCompleteIntro();
				Group_Name = groupInfo.getName();
				if(Group_Intro.contains("部落冲突")||Group_Intro.contains("coc")||Group_Intro.contains("COC")||Group_Intro.contains("Coc")||Group_Name.contains("Coc")||Group_Name.contains("COC")||Group_Name.contains("部落冲突")||Group_Name.contains("coc")) {
					Boolean updateScoureUserGroup = Score.updateScoureUserGroup(qq, "group", split,creName);
					if(updateScoureUserGroup) {
						if("永久授权".equals(creName)) {
							return new AjaxResult("兑换成功，群：“"+split+"”已购买永久自动进群套餐，现可以拉状态为‘自动同意’的机器人进群，机器人将直接同意加群。");
						}
						return new AjaxResult("兑换成功，群：“"+split+"”已可以拉‘自动同意’状态的机器人进群，机器人将直接同意加群。");
					}else {
						Integer update2 = Score.update(qq, number, true,"群状态修改失败。");
						msg+="兑换失败，系统繁忙。";
						if(update2!=2) {
							msg+="积分回退失败，请联系作者。";
						}
						return new AjaxResult(msg);
					}
				}else {
					msg +="兑换失败，你的群不满足规则，我们只服务于部落相关群聊！";
					Integer update2 = Score.update(qq, number, true,"群不符合规范");
					if(update2!=2) {
						msg+="积分回退失败，请联系作者。";
					}
				}
			} catch (Exception e) {
				msg +="兑换失败，无法查询到你的群信息，请公开你的群搜索功能，我才能审核你的群是否具备资格。";
				Integer update2 = Score.update(qq, number, true,"购买加群资格失败");
				if(update2!=2) {
					msg+="积分回退失败，请联系作者。";
				}
			}
		}else if(update==1){
			msg += "你积分不足"+number+",兑换失败。";
		}else {
			msg += "系统繁忙,兑换失败。";
		}
		return new AjaxResult(msg);
	}
	/***
	 * 购买QQ好友位
	 * @param qq	qq好友
	 * @param qu_Sum 购买的数量
	 * @param type  商品类型
	 * @param number 商品需要的积分
	 * @param msg 艾特机器人状态
	 * @return 
	 */
	private static AjaxResult QqUpdate(String qq, Integer qu_Sum, String type, Integer number, String msg) {
		Integer dateSum = qu_Sum*number;
		if(dateSum<0||qu_Sum>10||qu_Sum<=0) {
			return new AjaxResult(msg +"兑换失败，请输入符合规范的参数。");
		}
		Integer update = Score.update(qq, qu_Sum*number, false,"购买天使好友位");
		if(update==2) {//扣除成功
			Boolean updateScoureUser = Score.updateScoureUser(qq, type, qu_Sum);
			if(updateScoureUser) {
				msg+="兑换成功，你已增加天使"+qu_Sum+"个好友位。提示：请主动添加好友未满的天使，添加腾讯无法同意的好友也算一次添加哦，每天凌晨4天重新统计好友人数，添加错误的话，请明日再试。";
			}
		}else if(update==1){
			msg += "你积分不足"+qu_Sum*number+",兑换失败。";
		}else {
			msg += "系统繁忙,兑换失败。";
		}
		return new AjaxResult(msg);
	}
	/***
	 * 购买图灵机器人
	 * @param qqcode
	 * @param sum 购买次数
	 * @param number 需要的积分
	 * @param czQQ 
	 * @return
	 */
	private static AjaxResult TuLin(String qqcode,Integer sum,Integer number,String msg, String czQQ) {
		Integer dateSum = sum*number;
		if(dateSum<0) {
			return new AjaxResult(msg +"兑换失败，请输入符合规范的参数。");
		}
		Integer update = Score.update(qqcode, dateSum, false,"购买天使聊天服务"+sum+"天");
		if(update==2) {//获取成功
			RedisUtil utils = SpringContextUtil.getBean(RedisUtil.class);
			new XjMysqlJdbc().saveRedis(czQQ, utils, sum);
			msg +="兑换成功，QQ："+czQQ+"已兑换"+sum+"*24小时的智能聊天服务，本次扣除积分："+sum*number+"。";
		}else if(update==1){
			msg += "你积分不足"+sum*number+",兑换失败。";
		}else {
			msg += "系统繁忙,兑换失败。";
		}
		return new AjaxResult(msg);
	}
	
	/***
	 * 直接指令
	 * @param string
	 * @param qq
	 * @param group
	 * @return 
	 */
	private static AjaxResult Length2(String string, String qq, boolean group) {
			String msg = "";
			if(group) {
				msg+="[CQ:at,qq="+qq+"] ";
			}
			switch (string) {
			case "查询":
				msg += "您目前账户积分："+Score.get(qq);
				return new AjaxResult(msg);
			case "我的积分":
				msg += "您目前账户积分："+Score.get(qq);
				return new AjaxResult(msg);
			case "积分剩余":
				msg += "您目前账户积分："+Score.get(qq);
				return new AjaxResult(msg);
			case "查询余额":
				msg += "您目前账户积分："+Score.get(qq);
				return new AjaxResult(msg);
			case "余额":
				msg += "您目前账户积分："+Score.get(qq);
				return new AjaxResult(msg);
			case "情况":
				msg += "您目前账户积分："+Score.get(qq);
				return new AjaxResult(msg);
			case "聊天":
				msg += getTuLin(qq);
				return new AjaxResult(msg);
			case "购买记录":
				msg += "您目前可加天使数："+Score.getScoureUser("qq",qq);
				msg +="\n"+getTuLin(qq);
				List<String> scoreUser = Score.getScoreUser(qq);
				if(scoreUser.size()>0) {
					msg+="\n您兑换的群聊有：";
					for (String string2 : scoreUser) {
						msg+="\n● "+string2;
					}
				}
				return new AjaxResult(msg);
			case "兑换记录":
				msg += "您目前可加天使数："+Score.getScoureUser("qq",qq);
				msg +="\n"+getTuLin(qq);
				scoreUser = Score.getScoreUser(qq);
				if(scoreUser.size()>0) {
					msg+="\n您兑换的群聊有：";
					for (String string2 : scoreUser) {
						msg+="\n● "+string2;
					}
				}
				return new AjaxResult(msg);
			/*case "积分商城":
				msg = "[CQ:image,file=image/user/store.jpg]";
				return new AjaxResult(msg);
			case "商城":
				msg = "[CQ:image,file=image/user/store.jpg]";
				return new AjaxResult(msg);
			case "兑换列表":
				msg = "[CQ:image,file=image/user/store.jpg]";
				return new AjaxResult(msg);*/
			default:
				break;
			}
			return new AjaxResult(false, msg);
	}

	
	
	private static String getTuLin(String qq) {
		RedisUtil utils = SpringContextUtil.getBean(RedisUtil.class);
		long expire = utils.getExpire("Tulin"+qq);
		if(expire<=0) {
			return "您目前没有体验智能聊天的时间哦，使用积分兑换后天使才能和你聊天哦。";
		}else{
			String secondToTime = TimeUtils.secondToTime(expire);
			return "您智能聊天服务于："+secondToTime+"后结束。";
		}
	}
	/***
	 * 获取String 里面的数字
	 * @param number
	 * @return
	 */
	public static String getNumber(String number) {
		if(number==null) {
			return null;
		}
		String regEx="[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(number);
		String trim = m.replaceAll("").trim();
		return trim;
	}
}
